package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.commons.tool.utils.NumberUtils;
import com.mall.order.biz.callback.SendEmailCallback;
import com.mall.order.biz.callback.TransCallback;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.PromoSession;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.PromoSessionMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * create-date: 2019/8/1-下午5:01
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;

    @Autowired
    PromoSessionMapper promoSessionMapper;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public boolean isAsync() {
        return false;
    }

    /*
     * @description: 生成订单获得订单id
     * @return: boolean
     * @author: mabinbin
     * @date: 2021/8/25
     */
    @Override
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext orderContext = (CreateOrderContext) context;

        //往订单中插入一条数据
        Order order = new Order();
        // TODO 可以用发号器
        String orderId = globalIdGeneratorUtil.getNextSeq("Hairpin1", 5);
//        String orderId = UUID.randomUUID().toString();
        order.setOrderId(orderId);
        order.setPayment(orderContext.getOrderTotal());
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setUserId(orderContext.getUserId());
        order.setBuyerNick(orderContext.getBuyerNickName());// TODO 传入的context不包含
        orderMapper.insert(order);

        //获得订单商品详情表的id，仅对库存够的商品插入到购物车中
        ArrayList<Long> productsDetailId = new ArrayList<>();
        //插入订单商品表中（一个订单对应多个商品）
        List<CartProductDto> cartProductDtoList = orderContext.getCartProductDtoList();
        //首先获得购物车中中商品的list
        for (CartProductDto productDto : cartProductDtoList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setId(globalIdGeneratorUtil.getNextSeq("Hairpin2", 5));
            orderItem.setItemId(productDto.getProductId());
            orderItem.setOrderId(orderId);
            orderItem.setNum(productDto.getProductNum().intValue());
            orderItem.setTitle(productDto.getProductName());
            orderItem.setPrice(productDto.getSalePrice().doubleValue());
            orderItem.setTotalFee(productDto.getSalePrice().doubleValue() * productDto.getProductNum());
            orderItem.setPicPath(productDto.getProductImg());
            orderItem.setStatus(1); // TODO 直接定义详情表的状态（不用），orderItem的时间未保存
            orderItemMapper.insert(orderItem);

            productsDetailId.add(productDto.getProductId());
        }
        //然后封装到order_item中，插入到表中
        orderContext.setBuyProductIds(productsDetailId);
        orderContext.setOrderId(orderId);

        // TODO 处理下秒杀与普通购买
        //获得sessionId和yyyyMMdd
        String sessionId = "1";
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour >= 16) {
            sessionId = "2";
        }
        String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(new Date());

        Example example = new Example(PromoSession.class);
        example.createCriteria()
                .andEqualTo("sessionId",sessionId)
                .andEqualTo("yyyymmdd",yyyyMMdd);
        List<PromoSession> promoSessions = promoSessionMapper.selectByExample(example);
        PromoSession promoSession = promoSessions.get(0);
        //获得场次Id和产品Id
        Long psId = promoSession.getId();

        CartProductDto productDto = cartProductDtoList.get(0);
        Long productId = productDto.getProductId();
        String getOrderIdKey = orderContext.getUserId() + "-" + psId + "-" + productId;
        RBucket<Object> bucket = redissonClient.getBucket(getOrderIdKey);
        bucket.set(orderId);

        return true;
    }
}
